package edu.upol.paradise.hypervisor;

import java.io.IOException;

import org.apache.log4j.Logger;

public class ParadiseHypervisor implements Runnable{
	static final Logger log = Logger.getLogger(ParadiseHypervisor.class);
	public static void main(String[] args) throws Exception{
		ParadiseHypervisor hypervisor = new ParadiseHypervisor(args);
		hypervisor.run();
	}
	
	public static ParadiseHypervisor hypervisor;
	
	private HypervisorSettings settings;
	private boolean terminated = false;
	private NodeClusterList nodes;
	
	public ParadiseHypervisor(String[] args) throws Exception {
		log.info("Initializing Paradise Hypervisor");
		hypervisor = this;
		settings = HypervisorSettings.parse(args);
	}

	public void run() {
		log.info("Starting Paradise Hypervisor");
		if (settings.isInfoServer()){
			try {
				new HypervisorInfoService();
			} catch (IOException e) {
				log.error(e);
				log.debug(e, e);
				settings.setInfoServer(false);
			}
		}
		fillNodes();
		new HypervisorServiceDaemon(settings.getServiceThreads(), settings.getServerAddress());
		nodes.addClusterNode("8.8.8.8", 1234);
		nodes.addClusterNode("localhost", 54231);
		nodes.acquireNodesFromNodes();
		nodes.checkNodes();
		// test
		nodes.addClusterNode("8.8.8.8", settings.getServerAddress());
		nodes.addClusterNode("8.8.8.8", 1234);
		nodes.addClusterNode("8.8.8.8", 1235);
		nodes.addClusterNode("8.8.8.8", 1236);
		while (true)
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
	}

	private void fillNodes() {
		nodes = new NodeClusterList();
		// load from file
		
		// add localhost
		nodes.addClusterNode("localhost", settings.getServerAddress());
		
	}

	public HypervisorSettings getSettings() {
		return settings;
	}

	public boolean isRunning() {
		return !terminated;
	}

	public NodeClusterList getNodes() {
		return nodes;
	}

}
